package com.xfcode.api.page;

import com.xfcode.common.constant.HttpStatus;
import com.xfcode.common.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PageTable<T> extends Page {
    /***
     * 获取分页对象
     * @param pageTable
     * @param <T>
     * @return
     */
    public static <T> TableDataInfo getPageTable(Page pageTable) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(pageTable.getRecords());
        rspData.setTotal(pageTable.getTotal());
        return rspData;
    }

    /***
     * page对象转换信息
     * @param mybatisPlusPage
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> PageTable<T> build(Page mybatisPlusPage, Class<T> clazz) {
        PageTable resPage = new PageTable<>();
        BeanUtils.copyProperties(mybatisPlusPage, resPage);
        List<T> list = new ArrayList<>();
        mybatisPlusPage.getRecords().forEach(entity -> {
            try {
                T obj = clazz.newInstance();
                BeanUtils.copyProperties(entity, obj);
                list.add(obj);
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("初始化类失败");
            }
        });
        resPage.setRecords(list);
        return resPage;
    }

}
